package org.example.dao;

import org.example.entity.Teacher;
import org.example.util.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class StarDao {
    public static ArrayList<Teacher> findAllUser(){

        // 泛型
        ArrayList<Teacher> arrayList = new ArrayList<>();

        // 查询数据
        Connection connection = DButil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        String sql = "select * from teacher ";

        try {
            // 获取预处理对象
            statement = connection.prepareStatement(sql);

            // 执行SQL语句
            resultSet = statement.executeQuery();

            while (resultSet.next()){

                String Userid = resultSet.getString("Id");
                String Sname = resultSet.getString("Sname");
                String Gender = resultSet.getString("Sno");
                String Password = resultSet.getString("Gender");
                String Bookname = resultSet.getString("Prof");
                String Outdata = resultSet.getString("Address");
                String Backdata = resultSet.getString("Grade");

                // 数据持久化 ==> 实体类
                Teacher user = new Teacher();
                user.setId(Userid);
                user.setSname(Sname);
                user.setGender(Gender);
                user.setSno(Password);
                user.setProf(Bookname);
                user.setAddress(Outdata);
                user.setGrade(Backdata);

                arrayList.add(user);
            }

        } catch (java.sql.SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            DButil.close(resultSet, statement, connection);
        }

        return arrayList;
    }


    public static boolean  login(String Userid, String Password){
        Connection connection = DButil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        String sql = "select * from teacher where Id = ? and Sname =? ";

        boolean flag = false;

        try {
            // 获取预处理对象
            statement = connection.prepareStatement(sql);

            // 对SQL进行传参
            statement.setString(1, Userid);
            statement.setString(2, Password);

            // 执行SQL语句
            resultSet = statement.executeQuery();
//            statement.executeUpdate()
            if (resultSet.next()){
                flag = true;
            }

        } catch (java.sql.SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            DButil.close(resultSet, statement, connection);
        }

        return flag;
    }
}

